package leetcode_core.utils;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 自定义数据库连接池
 * 由于业务量比较小,因此保存一个连接池
 * @author: 张庭杰
 * @date: 2022年11月12日 20:56
 */
public class MySqlSessionFactory {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//注册JDBC驱动
            registerCloseConnection();//注册关闭数据库连接的函数
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private MySqlSessionFactory() {}
    private static Connection connection;
    private static final String URL = "jdbc:mysql://localhost:3306/orm?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";

    public static Connection getConnection(){
        if(connection == null){
            try {
                connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
                System.out.println("连接数据库成功");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    //程序结束时关闭连接池
    private static void registerCloseConnection(){
        Runtime runtime = Runtime.getRuntime();
        runtime.addShutdownHook(new Thread(() -> {
            System.out.println("程序结束,正在关闭数据库");
            if(connection != null){
                try {
                    connection.close();
                    System.out.println("数据库连接已经关闭");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }));
    }
}
